package cn.com.nes.site.service.product.handle;

import cn.com.nes.common.exception.BusinessException;
import cn.com.nes.mybatis.agent.ope.entity.ProductSeriesAndEnergy;
import cn.com.nes.site.entity.em.product.ProductAttributeEnum;
import cn.com.nes.site.entity.vo.product.SaveProductSeriesAndEnergyVO;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 产品品牌系列处理器
 */
@Service("productSeriesHandler")
public class ProductSeriesHandler extends ProductAttributeHandler {

    private static final Long PRODUCT_SERIES_ROOT_NODE_ID = 1L; // parentId=1L - 创今公司品牌名称

    @Override
    public Integer getNodeType() {
        return ProductAttributeEnum.BRAND.getKey();
    }

    @Override
    public Long addNode(SaveProductSeriesAndEnergyVO vo) {
        // 处理根节点
        vo.setParentId(Objects.isNull(vo.getParentId()) ? PRODUCT_SERIES_ROOT_NODE_ID : vo.getParentId());
        // 开始保存节点数据
        ProductSeriesAndEnergy productAttributeEntity = super.getProductAttributeEntity(vo);
        // 设置公司id:区分是品牌还是能源分类,品牌记录公司id,能源分类不记录
        productAttributeEntity.setCompanyId(ObjectUtil.isNotNull(vo.getOperateUserCompanyId()) ? vo.getOperateUserCompanyId() : vo.getCompanyId());
        productAttributeEntity.setEnergyType(null);

        Integer rows = productSeriesAndEnergyMapper.insert(productAttributeEntity);
        if (rows != 1) {
            throw new BusinessException("新增品牌系列失败!");
        }
        return productAttributeEntity.getId();
    }

    @Override
    public Long updateNode(SaveProductSeriesAndEnergyVO vo) {
        // 开始更新数据
        ProductSeriesAndEnergy productSeriesAndEnergy = new ProductSeriesAndEnergy();
        BeanUtils.copyProperties(vo, productSeriesAndEnergy);
        productSeriesAndEnergy.setEnergyType(null);
        productSeriesAndEnergy.setGmtModified(vo.getOperateDate());
        productSeriesAndEnergy.setGmtModifiedId(vo.getOperateUserId());

        Integer rows = productSeriesAndEnergyMapper.updateById(productSeriesAndEnergy);
        if (rows != 1) {
            throw new BusinessException("修改品牌系列失败!");
        }
        return productSeriesAndEnergy.getId();
    }
}
